/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.menu;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.mapper.query.NativeQuery;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.MetaResourceService;
import com.je.common.base.util.SecurityUserHolder;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.rpc.PermissionRpcService;
import com.je.rbac.service.permission.template.PcMenuDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/je/rbac/menu/quick")
public class QuickController extends AbstractPlatformController {

    @Autowired
    private PermissionRpcService permissionRpcService;
    @Autowired
    private PcMenuDataService pcMenuDataService;
    @Autowired
    private MetaResourceService metaResourceService;

    @RequestMapping(value = "/collectUserQuickMenu", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult collectUserQuickMenu(HttpServletRequest request) {
        String userId = getStringParameter(request, "userId");
        String menuId = getStringParameter(request, "menuId");
        String type = getStringParameter(request, "type");
        //设备类型：app，pc
        String deviceType = getStringParameter(request, "deviceType");
        deviceType = "app".equals(deviceType) ? "app" : "pc";
        if (Strings.isNullOrEmpty(userId)) {
            userId = SecurityUserHolder.getCurrentAccountId();
        }

        if (Strings.isNullOrEmpty(menuId)) {
            return BaseRespResult.errorResult("请选择要收藏的菜单！");
        }

        if (!"collect".equals(type) && !"uncollect".equals(type)) {
            return BaseRespResult.errorResult("请选择要进行的操作");
        }

        if ("collect".equals(type)) {
            DynaBean menuBean = metaService.selectOneByPk("JE_CORE_MENU", menuId);
            metaService.executeSql("UPDATE JE_CORE_KJMENU SET SY_ORDERINDEX=SY_ORDERINDEX+1 WHERE KJMENU_YHUD = {0} AND KJMENU_TYPE={1}", userId, deviceType);
            DynaBean quickMenuBean = new DynaBean("JE_CORE_KJMENU", false);
            quickMenuBean.set("KJMENU_YHUD", userId);
            quickMenuBean.set("KJMENU_CDID", menuId);
            quickMenuBean.set("SY_ORDERINDEX", 1);
            quickMenuBean.set("SY_STATUS", "1");
            quickMenuBean.set("KJMENU_TYPE", deviceType);
            quickMenuBean.set("SY_PRODUCT_ID", menuBean.getStr("SY_PRODUCT_ID"));
            quickMenuBean.set("SY_PRODUCT_CODE", menuBean.getStr("SY_PRODUCT_CODE"));
            quickMenuBean.set("SY_PRODUCT_NAME", menuBean.getStr("SY_PRODUCT_NAME"));
            commonService.buildModelCreateInfo(quickMenuBean);
            metaService.insert(quickMenuBean);
            return BaseRespResult.successResult("收藏成功！");
        }

        //将重复的删除
        metaService.delete("JE_CORE_KJMENU", ConditionsWrapper.builder().eq("KJMENU_YHUD", userId)
                .eq("KJMENU_CDID", menuId).eq("KJMENU_TYPE", deviceType));
        return BaseRespResult.successResult("取消收藏成功！");
    }

    @RequestMapping(value = "/loadUserQuickMenus", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult loadUserQuickMenus(HttpServletRequest request) {
        String departmentId = getStringParameter(request,"departmentId");
        String userId = getStringParameter(request, "userId");
        String tenantId = getStringParameter(request, "tenantId");
        String plan = getStringParameter(request, "plan");
        String deviceType = getStringParameter(request, "deviceType");
        deviceType = "app".equals(deviceType) ? "app" : "pc";
        if (Strings.isNullOrEmpty(userId)) {
            userId = SecurityUserHolder.getCurrentAccountId();
            departmentId = SecurityUserHolder.getCurrentAccountDepartment().getId();
            tenantId = SecurityUserHolder.getCurrentAccountTenantId();
        }

        ConditionsWrapper wrapper = ConditionsWrapper.builder();
        wrapper.table("JE_CORE_KJMENU");
        wrapper.eq("KJMENU_YHUD", userId);
        wrapper.eq("KJMENU_TYPE", deviceType);
        if (!Strings.isNullOrEmpty(plan)) {
            //过滤，必须有一级菜单才加载一级菜单下的收藏菜单
            DynaBean planBean = metaResourceService.selectOneByNativeQuery("JE_CORE_SETPLAN", NativeQuery.build().eq("JE_SYS_PATHSCHEME", plan));
            String topMenuId = planBean.getStr("SETPLAN_ASSOCIATE_TOP_MENU_ID");
            String isAssociateAllTopMenu = planBean.getStr("SETPLAN_ASSOCIATE_ALL_TOP_MENU", "1");
            if (!Strings.isNullOrEmpty(topMenuId) && !isAssociateAllTopMenu.equals("1")) {
                List<DynaBean> headmenu_relation = metaService.select("JE_RBAC_HEADMENU_RELATION",
                        ConditionsWrapper.builder().in("JE_RBAC_HEADMENU_ID", Splitter.on(",").splitToList(topMenuId)), "RELATION_MENUMODULE_ID");
                List<DynaBean> menuIds = metaService.select("JE_CORE_MENU", ConditionsWrapper.builder()
                        .apply(String.format("JE_CORE_MENU_ID IN ( SELECT KJMENU_CDID FROM JE_CORE_KJMENU WHERE KJMENU_YHUD = '%s' )", userId))
                        .and(inWrapper -> {
                            for (int i = 0; i < headmenu_relation.size(); i++) {
                                if (i > 0) {
                                    inWrapper.or();
                                }
                                inWrapper.like("SY_PATH", headmenu_relation.get(i).getStr("RELATION_MENUMODULE_ID"));
                            }
                        }), "JE_CORE_MENU_ID"
                );
                if (menuIds.size() > 0) {
                    String[] menuIdArr = new String[menuIds.size()];
                    for (int i = 0; i < menuIdArr.length; i++) {
                        menuIdArr[i] = menuIds.get(i).getStr("JE_CORE_MENU_ID");
                    }
                    wrapper.in("KJMENU_CDID", menuIdArr);
                }
            }
        }
        List<Map<String, Object>> quickBeanList = metaService.selectSql(wrapper.orderByAsc("SY_ORDERINDEX"));
        List<String> menuPermissionList = permissionRpcService.findAccountMenuPermissions(departmentId,userId, tenantId);
        List<Map<String, Object>> permdList = new ArrayList<>();
        for (Map<String, Object> eachMap : quickBeanList) {
            if (!menuPermissionList.contains(pcMenuDataService.formatMenuDataShowTemplate(eachMap.get("KJMENU_CDID").toString()))) {
                continue;
            }
            permdList.add(eachMap);
        }
        return BaseRespResult.successResult(permdList);
    }

    @RequestMapping(value = "/updateQuickMenus", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult updateQuickMenus(HttpServletRequest request) {
        String userId = getStringParameter(request, "userId");
        String menuIds = getStringParameter(request, "menuIds");
        String deviceType = getStringParameter(request, "deviceType");
        deviceType = "app".equals(deviceType) ? "app" : "pc";
        if (Strings.isNullOrEmpty(menuIds)) {
            return BaseRespResult.errorResult("请选择要更新的菜单！");
        }

        if (Strings.isNullOrEmpty(userId)) {
            userId = SecurityUserHolder.getCurrentAccountId();
        }

        List<String> menuIdList = Splitter.on(",").splitToList(menuIds);
        metaService.delete("JE_CORE_KJMENU", ConditionsWrapper.builder()
                .eq("KJMENU_YHUD", userId).eq("KJMENU_TYPE", deviceType)
                .in("KJMENU_CDID", menuIdList));
        for (int i = 0; i < menuIdList.size(); i++) {
            DynaBean quickMenuBean = new DynaBean("JE_CORE_KJMENU", false);
            quickMenuBean.set("KJMENU_YHUD", userId);
            quickMenuBean.set("KJMENU_CDID", menuIdList.get(i));
            quickMenuBean.set("SY_ORDERINDEX", i + 1);
            quickMenuBean.set("SY_STATUS", "1");
            quickMenuBean.set("KJMENU_TYPE", deviceType);
            commonService.buildModelCreateInfo(quickMenuBean);
            metaService.insert(quickMenuBean);
        }
        return BaseRespResult.successResult("更新成功！");
    }

    @RequestMapping(value = "/removeQuickMenus", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult removeQuickMenus(HttpServletRequest request) {
        String userId = getStringParameter(request, "userId");
        String menuIds = getStringParameter(request, "menuIds");
        String deviceType = getStringParameter(request, "deviceType");
        deviceType = "app".equals(deviceType) ? "app" : "pc";
        if (Strings.isNullOrEmpty(userId)) {
            userId = SecurityUserHolder.getCurrentAccountId();
        }
        if (Strings.isNullOrEmpty(menuIds)) {
            return BaseRespResult.errorResult("请选择要删除的快捷菜单！");
        }

        List<String> menuIdList = Splitter.on(",").splitToList(menuIds);
        metaService.delete("JE_CORE_KJMENU", ConditionsWrapper.builder()
                .eq("KJMENU_YHUD", userId).eq("KJMENU_TYPE", deviceType)
                .in("KJMENU_CDID", menuIdList));
        return BaseRespResult.successResult("取消收藏成功！");
    }


}
